package hu.dobrosi.util.io;

import java.io.IOException;
import java.io.InputStream;

public class BufferedInputStreamReader {

	private InputStream in;
	private int timeout;

	public BufferedInputStreamReader(InputStream in) throws IOException {
		this(in, -1);
	}

	public BufferedInputStreamReader(InputStream in, int timeout)
			throws IOException {
		this.in = in;
		this.timeout = timeout;
	}

	public int read(byte[] b, int off, int len) throws IOException {
		return in.read(b, off, len);
	}

	public int read(byte[] b) throws IOException {
		return in.read(b);
	}

	public String readLine(boolean waitFor) throws IOException {
		long startTime = System.currentTimeMillis();
		String res = null;
		int ch = -1;
		boolean virgin = true;
		do {
			if (ch != -1) {
				if (ch != '\r' && ch != '\n') {
					if (virgin) {
						res = "";
					}
					virgin = false;
					res += (char) ch;
				} else if (ch == '\n') {
					return res == null ? "" : res;
				}
			}
			ch = in.read();
		} while ((waitFor || in.available() > 0)
				&& (timeout < 0 || startTime + timeout > System
						.currentTimeMillis()));
		return res;
	}

	public String readLine() throws IOException {
		return readLine(true);
	}

	public void close() throws IOException {
		in.close();
	}
}
